package com.shawn.springboot.integeration.websocket.server;

import com.shawn.springboot.integeration.websocket.session.WebSocketSessions;
import com.shawn.springboot.integeration.websocket.util.SemaphoreUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.Semaphore;

/**
 * websocket 消息处理
 *
 * @author ruoyi
 */
@Component
@ServerEndpoint("/websocket/message")
@Slf4j
public class WebSocketServer {
    /** 默认最多允许同时在线会话数 100 **/
    public static int maxOnlineCount = 100;
    /** 信号量,用户控制同时在线人数 **/
    private static Semaphore socketSemaphore = new Semaphore(maxOnlineCount);
    @OnOpen
    public void onOpen(Session session) throws Exception {
        boolean semaphoreFlag;
        // 尝试获取信号量
        semaphoreFlag = SemaphoreUtils.tryAcquire(socketSemaphore);
        if (!semaphoreFlag) {   // 未获取到信号量
            log.error("\n 当前在线人数超过限制数- {}", maxOnlineCount);
            String rspMsg = "当前在线人数超过限制数：" + maxOnlineCount;
            WebSocketSessions.sendMsgToUserByText(session, rspMsg);
            session.close();
        } else { // 获取到信号量,则添加用户
            WebSocketSessions.put(session.getId(), session);
            log.info("\n 建立连接 - {}", session);
            log.info("\n 当前人数 - {}", WebSocketSessions.getSessions().size());
            WebSocketSessions.sendMsgToUserByText(session, "连接成功");
        }
    }

    @OnClose
    public void onClose(Session session) {
        log.info("\n 关闭连接 - {}", session);
        // 移除用户
        WebSocketSessions.remove(session.getId());
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }

    @OnError
    public void onError(Session session, Throwable exception)
            throws Exception {
        if (session.isOpen()) {     //异常时,连接还在则关闭
            session.close();
        }
        String sessionId = session.getId();
        log.error("连接[{}]异常",sessionId,exception);
        // 移出用户
        WebSocketSessions.remove(sessionId);
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }
    @OnMessage
    public void onMessage(String message, Session session) {
        // 自定义逻辑处理
        String msg = message.replace("你", "我")
                .replace("吗", "");
        // 发送返回消息给会话客户端
        WebSocketSessions.sendMsgToUserByText(session, msg);
    }
}
